<?php
/**
 * Created by PhpStorm.
 * Use : 扫描FTP服务器片源媒体文件信息至上游消息队列
 * User: kan.yang@starcor.com
 * Date: 18-6-1
 * Time: 上午11:13
 */
header("Content-type: text/html; charset=utf-8");
set_time_limit(0);
//基路径
$str_base_path = dirname(dirname(dirname(dirname(dirname(__DIR__)))));
//引入文件
include_once $str_base_path . "/v2/common.php";
include_once $str_base_path . '/mgtv_v2/mgtv_init.php';
include_once $str_base_path . '/api_v2/nn_const.php';
include_once $str_base_path . '/api_v2/common.php';
include_once $str_base_path . '/nn_logic/nl_common.func.php';
include_once $str_base_path . '/nn_logic/nl_log_v2.func.php';
include_once $str_base_path . '/nn_logic/cp/cp.class.php';
include_once $str_base_path . '/nn_class/encrypt/encrypt_aes.class.php';

\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load_old("nn_class/ftp/ftp.class.php");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load_old("nn_logic/queue/queue_redis.class.php");

class import_ftp_media extends ns_model\message\message_queue
{
    private $obj_dc = null;
    //CP ID
    private $str_cp_id = '';
    //客户端传递参数
    private $arr_client_params = array();
    //注入消息队列模板
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'1', //xml文件中包含的内容数量
            'nns_message_state'=>0,
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    /**
     * 默认构造函数
     */
    public function __construct($str_params = null)
    {
        //解析JSON字符串
        if(isset($str_params) && !empty($str_params))
        {
            $arr_client_params = explode(')(',stripslashes($str_params));
            if(is_array($arr_client_params) && !empty($arr_client_params))
            {
                foreach($arr_client_params as $val)
                {
                    $arr_val = explode('=',$val);
                    $this->arr_client_params[$arr_val[0]] = $arr_val[1];
                }
            }
        }
        //CP ID
        $arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
        $this->str_cp_id = array_pop($arr_dir);
        //初始化obj DC
        m_config::get_dc();

        $this->obj_dc = nl_get_dc(array (
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_NULL
        ));
    }

    /**
     * 入口函数
     */
    public function init()
    {
        //查询CP信息
        $result_cp_config = m_config::_get_cp_info($this->str_cp_id);
        if($result_cp_config['ret'] != 0 || empty($result_cp_config['data_info']))
        {
            return m_config::return_data(1,"CP[" . $this->str_cp_id . "]：获取CP信息为空");
        }
        else
        {
            $result_cp_config = $result_cp_config['data_info'];
        }
        $this->arr_in_message['base_info']['nns_cp_id'] = $this->str_cp_id;
        //FTP请求地址
        $str_ftp_path = isset($this->arr_client_params['ftp_url']) ? $this->arr_client_params['ftp_url'] : '';
        //CP自定义FTP信息
        if(isset($result_cp_config['nns_config']['message_ftp_import_enable']) && $result_cp_config['nns_config']['message_ftp_import_enable'] == 1)
        {
            if(isset($result_cp_config['nns_config']['message_ftp_import_file_url']) && strlen($result_cp_config['nns_config']['message_ftp_import_file_url']) > 0)
            {
                $str_ftp_path = $result_cp_config['nns_config']['message_ftp_import_file_url'];
            }
        }
        //验证FTP地址是否有效
        if(!isset($str_ftp_path) && strlen($str_ftp_path) > 0)
        {
            return m_config::return_data(1,"CP[" . $this->str_cp_id . "]：FTP地址配置为空");
        }
        $str_ftp_path = rtrim($str_ftp_path,'/') . '/' . $this->str_cp_id;
        //缓存KEY
        $str_cache_key = nl_view_cache::gkey('message_ftp_import_file_url_'.$this->str_cp_id,array('message_ftp_import_file_url_'.$this->str_cp_id,__FILE__));
        //获取缓存数据
        $result_redis = nl_queue_redis::pop(m_config::get_redis_dc(), $str_cache_key);
        //验证是否需要扫描硬盘
        if($result_redis['ret'] != 0 || !isset($result_redis['data_info']) || empty($result_redis['data_info']))
        {
            return $this->_ftp_get_files($str_ftp_path,$str_cache_key);
        }
        else
        {
            $arr_file_list = json_decode($result_redis['data_info'],true);
        }
        //获取TAG分组
        $str_tag = isset($this->arr_client_params['media_tag']) ? $this->arr_client_params['media_tag'] : '';
        //清晰度
        $str_mode= isset($this->arr_client_params['media_mode']) ? $this->arr_client_params['media_mode'] : '';
        //码率
        $str_bitrate = isset($this->arr_client_params['bitrate']) ? $this->arr_client_params['bitrate'] : '2300';
        //分辨率
        $str_resolution = isset($this->arr_client_params['resolution']) ? $this->arr_client_params['resolution'] : '1024*768';
        //遍历入库
        $str_video_id = $str_index_id = $str_media_id = '';
        foreach ($arr_file_list as $file)
        {
            $int_video_max_index = 0;$str_release_time = '0000-00-00';
            //主媒资：影片名称 + CP ID
            $str_video_id = MD5($file['nns_video_name'] . $this->str_cp_id);
            //分集 + 片源
            if(isset($file['nns_video_file']) && !empty($file['nns_video_file']))
            {
                foreach($file['nns_video_file'] as $value)
                {
                    $arr_file_info = pathinfo($value['nns_url']);
                    if(!isset($arr_file_info) || empty($arr_file_info))
                    {
                        continue;
                    }
                    //上映时间
                    $str_release_time = $value['nns_release_time'];
                    //分集
                    $str_index_name = $arr_file_info['filename'];
                    //获取分集号
                    $int_split_index = strripos($str_index_name,'_');
                    if($int_split_index !== false)
                    {//文件名称：有别名，如：***_1-1

                        $str_index  = substr($str_index_name,$int_split_index + 1,strlen($str_index_name) - 1);
                        $str_file_name  = substr($str_index_name,0,$int_split_index);
                    }
                    else
                    {//文件名称格式：无别名，如：1-1

                        $str_index = $str_index_name;
                        $str_file_name = $file['nns_video_name'];
                    }
                    $str_index_name = $file['nns_video_name'];
                    $int_index = explode('-',$str_index);
                    $int_index = count($int_index) > 0 && is_numeric($int_index[0]) ? $int_index[0] : 1;
                    $str_index_name.= '_' . $int_index;
                    $str_file_name .= '_' . $int_index;
                    $str_index_id = MD5($str_index_name . $this->str_cp_id);
                    $result = $this->_insert_index_message($value,$str_video_id,$str_index_id,$str_file_name,$int_index,$str_tag);
                    //片源
                    if($result['ret'] == 0)
                    {
                        //码率
                        $value['nns_bit_rate'] = $str_bitrate;
                        //分辨率
                        $value['nns_resolution'] = $str_resolution;
                        $this->_insert_media_message($value,$str_video_id,$str_index_id,$str_file_name . '_' . $str_index,$arr_file_info['extension'],$str_mode,$str_tag);
                        //主媒资最新分集号
                        $int_video_max_index = $int_video_max_index < $int_index ? $int_index : $int_video_max_index;
                    }
                    usleep(10000);
                }
            }
            //主媒资
            $this->_insert_video_message($file,$str_video_id,$str_release_time,$str_tag,$int_video_max_index);
        }

        return m_config::return_data(0,'ok');
    }

    /**
     * 获取FTP文件
     * @param string $str_ftp_path            FTP文件路径
     * @param string $str_cache_key           缓存KEY
     * @param int    $int_ftp_import_num      分页条数
     * @param array  $arr_file_ex             允许扩展名
     * @return array('ret' => 0/1,'reason' => '描述信息')
     */
    private function _ftp_get_files($str_ftp_path,$str_cache_key,$int_ftp_import_num = 100,$arr_file_ex = array('ts','mp4','mp3','m3u8'))
    {
        $arr_files = null;
        $ftp_url = trim($str_ftp_path,'/');
        $arr_ftp_config = parse_url($ftp_url);
        $host_ftp = (isset($arr_ftp_config["host"]) && strlen($arr_ftp_config["host"]) > 0) ? $arr_ftp_config["host"] : '';
        $user_ftp = (isset($arr_ftp_config["user"]) && strlen($arr_ftp_config["user"]) > 0) ? $arr_ftp_config["user"] : '';
        $pass_ftp = (isset($arr_ftp_config["pass"]) && strlen($arr_ftp_config["pass"]) > 0) ? $arr_ftp_config["pass"] : '';
        $path_ftp = (isset($arr_ftp_config["path"]) && strlen($arr_ftp_config["path"]) > 0) ? $arr_ftp_config["path"] : '';
        $port_ftp = (isset($arr_ftp_config["port"]) && strlen($arr_ftp_config["port"]) > 0) ? $arr_ftp_config["port"] : 21;
        $obj_ftp = new nl_ftp($host_ftp, $user_ftp, $pass_ftp,$port_ftp);
        //链接FTP
        $result_conn = $obj_ftp->base_opration_ftp();
        if(!$result_conn)
        {
            return m_config::return_data(1,"ftp链接失败,原因：".var_export($obj_ftp->make_error_data(),true));
        }
        //获取FTP基地址
        if(strlen($path_ftp) > 0)
        {
            $ftp_url = trim(substr($ftp_url,0, (-strlen($path_ftp))),'/');
        }
        //获取可扫描的文件目录
        $str_path_ftp = $obj_ftp->get_valid_recursive_path($ftp_url,$path_ftp);
        if(empty($str_path_ftp))
        {
            return m_config::return_data(1,"ftp文件相对路径[{$ftp_url}]：文件目录均已被扫描或文件目录不存在任何文件");
        }
        $str_path_ftp = rtrim($str_path_ftp,'/') . '/';
        //扫描文件目录
        $arr_scan_files = array(); $obj_ftp_conn = $obj_ftp->get_ftp_conn();
        $this->_ftp_recursive_file_listing($obj_ftp_conn,$ftp_url,$arr_scan_files,$str_path_ftp,$arr_file_ex);
        //临时日志
        m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 扫盘结束：' . (empty($result) ? '失败' : '成功'));
        //是否存在文件
        if(empty($arr_scan_files) || !is_array($arr_scan_files))
        {
            return m_config::return_data(1,"未查询到任何文件信息,相对路径[{$ftp_url}]");
        }
        //除去影片栏目目录，仅留下片源文件上级目录
        $arr_files = array();
        $this->_handle_files_level($arr_scan_files,$arr_files);
        //分页限制
        if(is_array($arr_files) && !empty($arr_files))
        {
            $arr_files = array_chunk($arr_files,$int_ftp_import_num);
        }
        if(is_array($arr_files) && !empty($arr_files))
        {
            foreach ($arr_files as $val_file)
            {
                if(empty($val_file) || !is_array($val_file))
                {
                    continue;
                }
                $val_file = json_encode($val_file,true);
                $result = nl_queue_redis::push(m_config::get_redis_dc(), $str_cache_key, $val_file);
                if($result['ret'] != 0)
                {
                    return $result;
                }
            }
        }
        //临时日志
        m_config::base_write_log('message','request',date('Y-m-d H:i:s') . ' 扫盘结束：' . (empty($arr_files) ? '存放Redis失败' : '存放Redis成功'));
        unset($arr_files);
        //更新已扫描的标志位状态
        $obj_ftp->modify_valid_flag_file($str_path_ftp,1);
        return m_config::return_data(0,"OK,ftp文件相对路径[{$ftp_url}]");
    }

    /**
     * 扫描FTP文件目录的文件
     */
    private function _ftp_recursive_file_listing($ftp_conn,$ftp_url,&$arr_files,$str_path,$arr_extension)
    {
        //获取文件目录
        $contents = ftp_nlist($ftp_conn, $str_path);
        usleep(50000);
        if(empty($contents) || !is_array($contents))
        {
            return null;
        }
        //遍历目录
        foreach ($contents as $currentFile)
        {
            if (strpos($currentFile, '.') === false)
            {
                //父级文件名称不为空
                $arr_dir_info = pathinfo($currentFile);
                if(isset($arr_dir_info['filename']) && !empty($arr_dir_info['filename']))
                {
                    $str_video_name = $this->_handle_iconv_encoding($arr_dir_info['filename']);
                    $str_dir_name = MD5($str_video_name);
                    $arr_files[$str_dir_name] = array(
                        'nns_video_name' => $str_video_name,
                        'nns_video_file' => array(),
                        'nns_file_url'   => $this->_handle_iconv_encoding($currentFile),
                    );
                    $this->_ftp_recursive_file_listing($ftp_conn,$ftp_url,$arr_files[$str_dir_name]['nns_video_file'],$currentFile,$arr_extension);
                }
            }
            else
            {
                if(!empty($arr_extension))
                {
                    $temp_file_url = pathinfo($currentFile);
                    if(!isset($temp_file_url['extension']) || !in_array(strtolower($temp_file_url['extension']),$arr_extension))
                    {
                        continue;
                    }
                }
                //时间戳
                $int_time = ftp_mdtm($ftp_conn,$currentFile);
                //字节
                $int_size = ftp_size($ftp_conn,$currentFile);
                $arr_file = array(
                    'nns_url'       => $this->_handle_iconv_encoding(rtrim($ftp_url,'/') . '/' . ltrim($currentFile,'/')),
                    'nns_file_size' => $int_size < 0 ? 0 : round($int_size / 1024,2),
                    'nns_release_time' => $int_time < 0 ? '0000-00-00' : date('Y-m-d',$int_time),
                );
                $arr_files['nns_files'][] = $arr_file;
                if(!isset($arr_files['nns_leaf']))
                {
                    $arr_files['nns_leaf'] = 1;
                }
            }
        }
        unset($contents);
    }

    /**
     * 过滤初次扫描文件后的父级栏目
     */
    private function _handle_files_level($arr_old_files,&$arr_handle_files)
    {
        if(!is_array($arr_old_files) || empty($arr_old_files))
        {
            return false;
        }
        //遍历处理
        foreach($arr_old_files as $file)
        {
            if(!isset($file['nns_video_file']) || empty($file['nns_video_file']))
            {
                continue;
            }
            if(isset($file['nns_video_file']['nns_leaf']) && $file['nns_video_file']['nns_leaf'] == 1)
            {
                unset($file['nns_video_file']['nns_leaf']);
                $file['nns_video_file'] = $file['nns_video_file']['nns_files'];
                $arr_handle_files[] = $file;
            }
            else
            {
                $this->_handle_files_level($file['nns_video_file'],$arr_handle_files);
            }
        }
        return true;
    }

    /**
     * 构建主媒资XML内容
     * @param array $arr_series_params array(
            'nns_video_id'     => 影片ID,
            'nns_video_name'   => 影片名称,
            'nns_category_name'=> 所属栏目,
            'nns_release_time' => 上映时间,
            'nns_view_type'    => 影片类型,
            'nns_view_len'     => 影片时长（秒）,
            'nns_all_index'    => 影片总集数,
            'nns_new_index'    => 影片最新集数,
            'nns_tag'          => EPG分组,
     * )
     * @return string 主媒资ADI文件内容
     */
    private function _do_series($arr_series_params)
    {
        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $str_xml .=     '<Objects>';
        $str_xml .=         '<Object ElementType="Series" ID="' . $arr_series_params['nns_video_id'] . '" Action="REGIST">';
        $str_xml .=             '<Property Name="Name">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="OrderNumber"/>';
        $str_xml .=             '<Property Name="OriginalName">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="AliasName">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="EnglishName"/>';
        $str_xml .=             '<Property Name="SortName">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="SearchName">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="OrgAirDate"/>';
        $str_xml .=             '<Property Name="ReleaseYear">' . $arr_series_params['nns_release_time'] . '</Property>';
        $str_xml .=             '<Property Name="LicensingWindowStart"/>';
        $str_xml .=             '<Property Name="LicensingWindowEnd"/>';
        $str_xml .=             '<Property Name="CPContentID">' . $this->str_cp_id . '</Property>';
        $str_xml .=             '<Property Name="DisplayAsNew">0</Property>';
        $str_xml .=             '<Property Name="DisplayAsLastChance">0</Property>';
        $str_xml .=             '<Property Name="Macrovision">1</Property>';
        $str_xml .=             '<Property Name="Price"/>';
        $str_xml .=             '<Property Name="VolumnCount">' . $arr_series_params['nns_all_index'] . '</Property>';
        $str_xml .=             '<Property Name="NewCount">' . $arr_series_params['nns_new_index'] . '</Property>';
        $str_xml .=             '<Property Name="Status">1</Property>';
        $str_xml .=             '<Property Name="Description"/>';
        $str_xml .=             '<Property Name="ContentProvider">' . $this->str_cp_id . '</Property>';
        $str_xml .=             '<Property Name="KeyWords">' . $arr_series_params['nns_video_name'] . '</Property>';
        $str_xml .=             '<Property Name="OriginalCountry"/>';
        $str_xml .=             '<Property Name="ActorDisplay"/>';
        $str_xml .=             '<Property Name="WriterDisplay"/>';
        $str_xml .=             '<Property Name="Language"/>';
        $str_xml .=             '<Property Name="Kind"/>';
        $str_xml .=             '<Property Name="Duration">' . $arr_series_params['nns_view_len'] . '</Property>';
        $str_xml .=             '<Property Name="CategoryName">' . $arr_series_params['nns_category_name'] . '</Property>';
        $str_xml .=             '<Property Name="CategoryID"/>';
        $str_xml .=             '<Property Name="PlayCount">0</Property>';
        $str_xml .=             '<Property Name="CategorySort">0</Property>';
        $str_xml .=             '<Property Name="Tags">' . $arr_series_params['nns_tag'] . '</Property>';
        $str_xml .=             '<Property Name="ViewPoint"></Property>';
        $str_xml .=             '<Property Name="StarLevel">6</Property>';
        $str_xml .=             '<Property Name="Rating"/>';
        $str_xml .=             '<Property Name="Awards"/>';
        $str_xml .=             '<Property Name="Sort">0</Property>';
        $str_xml .=             '<Property Name="Hotdegree">0</Property>';
        $str_xml .=             '<Property Name="Reserve1"/>';
        $str_xml .=             '<Property Name="Reserve1"/>';
        $str_xml .=         '</Object>';
        $str_xml .=     '</Objects>';
        $str_xml .= '</ADI>';

        return $str_xml;
    }

    /**
     * 构建分集XML内容
     * @param string $str_video_id        主媒资ID
     * @param array  $arr_program_params  array(
            'nns_index_id'    => 分集ID,
            'nns_index_name'  => 分集名称,
            'nns_sequence'    => 分集号,
            'nns_release_time'=> 上映时间,
            'nns_view_len'    => 分集时长（秒）,
            'nns_tag'         => EPG分组,
     * )
     * @return string 分集ADI文件内容
     */
    private function _do_program($str_video_id,$arr_program_params)
    {
        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $str_xml .=     '<Objects>';
        $str_xml .=         '<Object ElementType="Program" ID="' . $arr_program_params['nns_index_id'] . '" Action="REGIST">';
        $str_xml .=             '<Property Name="Name">' . $arr_program_params['nns_index_name'] . '</Property>';
        $str_xml .=             '<Property Name="CPContentID">' . $this->str_cp_id . '</Property>';
        $str_xml .=             '<Property Name="OrderNumber"/>';
        $str_xml .=             '<Property Name="OriginalName">' . $arr_program_params['nns_index_name'] . '</Property>';
        $str_xml .=             '<Property Name="SortName"/>';
        $str_xml .=             '<Property Name="Sequence">' . $arr_program_params['nns_sequence'] . '</Property>';
        $str_xml .=             '<Property Name="SortName"/>';
        $str_xml .=             '<Property Name="SearchName">' . $arr_program_params['nns_index_name'] . '</Property>';
        $str_xml .=             '<Property Name="ActorDisplay"/>';
        $str_xml .=             '<Property Name="OriginalCountry"/>';
        $str_xml .=             '<Property Name="Language"/>';
        $str_xml .=             '<Property Name="ReleaseYear">' . $arr_program_params['nns_release_time'] . '</Property>';
        $str_xml .=             '<Property Name="OrgAirDate">' . $arr_program_params['nns_release_time'] . '</Property>';
        $str_xml .=             '<Property Name="LicensingWindowStart"/>';
        $str_xml .=             '<Property Name="LicensingWindowEnd"/>';
        $str_xml .=             '<Property Name="DisplayAsNew"/>';
        $str_xml .=             '<Property Name="DisplayAsLastChance"/>';
        $str_xml .=             '<Property Name="Macrovision">1</Property>';
        $str_xml .=             '<Property Name="Description"/>';
        $str_xml .=             '<Property Name="PriceTaxIn"/>';
        $str_xml .=             '<Property Name="Status">1</Property>';
        $str_xml .=             '<Property Name="SourceType">1</Property>';
        $str_xml .=             '<Property Name="SeriesFlag">1</Property>';
        $str_xml .=             '<Property Name="ContentProvider">' . $this->str_cp_id . '</Property>';
        $str_xml .=             '<Property Name="KeyWords">' . $arr_program_params['nns_index_name'] . '</Property>';
        $str_xml .=             '<Property Name="Tags">' . $arr_program_params['nns_tag'] . '</Property>';
        $str_xml .=             '<Property Name="ViewPoint"/>';
        $str_xml .=             '<Property Name="StarLevel"/>';
        $str_xml .=             '<Property Name="Rating"/>';
        $str_xml .=             '<Property Name="Awards"/>';
        $str_xml .=             '<Property Name="Duration">' . $arr_program_params['nns_view_len'] . '</Property>';
        $str_xml .=             '<Property Name="Reserve1"/>';
        $str_xml .=             '<Property Name="Reserve2"/>';
        $str_xml .=             '<Property Name="Reserve3"/>';
        $str_xml .=             '<Property Name="Reserve4"/>';
        $str_xml .=             '<Property Name="Reserve5"/>';
        $str_xml .=         '</Object>';
        $str_xml .=     '</Objects>';
        $str_xml .=         '<Mappings>';
        $str_xml .=             '<Mapping ParentType="Series" ParentID="' . $str_video_id . '" ElementType="Program" ElementID="' . $arr_program_params['nns_index_id'] . '" ParentCode="' . $str_video_id . '" ElementCode="' . $arr_program_params['nns_index_id'] . '" Action="REGIST" Type="1">';
        $str_xml .=             '<Property Name="Sequence">' . $arr_program_params['nns_sequence'] . '</Property>';
        $str_xml .=         '</Mapping>';
        $str_xml .=     '</Mappings>';
        $str_xml .= '</ADI>';

        return $str_xml;
    }

    /**
     * 构建片源XML内容
     * @param string $str_video_id     影片ID
     * @param string $str_index_id     分集ID
     * @param array  $arr_movie_params array(
            'nns_movie_id'     => 片源ID,
            'nns_movie_url'    => 片源名称,
            'nns_screen_format'=> 编码格式,
            'nns_file_len'     => 片源时长（秒）,
            'nns_file_size'    => 片源大小（KB）,
            'nns_resolution'   => 片源分辨率,
            'nns_bit_rate'     => 片源码率,
            'nns_movie_mode'   => 片源清晰度,
            'nns_system_layer' => 文件格式,
            'nns_tag'          => EPG分组,
     * )
     * @return string 片源ADI文件内容
     */
    private function _do_movie($str_video_id,$str_index_id,$arr_movie_params)
    {
        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $str_xml .=     '<Objects>';
        $str_xml .=         '<Object ElementType="Movie" ID="' . $arr_movie_params['nns_movie_id'] . '" Action="REGIST" Type="1">';
        $str_xml .=             '<Property Name="FileURL">' . $arr_movie_params['nns_movie_url'] . '</Property>';
        $str_xml .=             '<Property Name="CPContentID">' . $this->str_cp_id . '</Property>';
        $str_xml .=             '<Property Name="SourceDRMType">0</Property>';
        $str_xml .=             '<Property Name="DestDRMType">0</Property>';
        $str_xml .=             '<Property Name="AudioType">1</Property>';
        $str_xml .=             '<Property Name="ScreenFormat">' . $arr_movie_params['nns_screen_format'] . '</Property>';
        $str_xml .=             '<Property Name="ClosedCaptioning">1</Property>';
        $str_xml .=             '<Property Name="Tags">' . $arr_movie_params['nns_tag'] . '</Property>';
        $str_xml .=             '<Property Name="Duration">' . $arr_movie_params['nns_file_len'] . '</Property>';
        $str_xml .=             '<Property Name="FileSize">' . $arr_movie_params['nns_file_size'] . '</Property>';
        $str_xml .=             '<Property Name="BitRateType">' . $arr_movie_params['nns_bit_rate'] . '</Property>';
        $str_xml .=             '<Property Name="VideoType"/>';
        $str_xml .=             '<Property Name="AudioEncodingType">4</Property>';
        $str_xml .=             '<Property Name="Resolution">' . $arr_movie_params['nns_resolution'] . '</Property>';
        $str_xml .=             '<Property Name="MediaMode">' . $arr_movie_params['nns_movie_mode'] . '</Property>';
        $str_xml .=             '<Property Name="SystemLayer">' . $arr_movie_params['nns_system_layer'] . '</Property>';
        $str_xml .=             '<Property Name="ServiceType"/>';
        $str_xml .=             '<Property Name="Domain"/>';
        $str_xml .=             '<Property Name="Hotdegree">0</Property>';
        $str_xml .=         '</Object>';
        $str_xml .=     '</Objects>';
        $str_xml .=     '<Mappings>';
        $str_xml .=         '<Mapping ParentType="Program" ParentID="' . $str_index_id . '" ElementType="Movie" ElementID="' . $arr_movie_params['nns_movie_id'] . '" ParentCode="' . $str_index_id . '" ElementCode="' . $arr_movie_params['nns_movie_id'] . '" Action="REGIST" Type="1"/>';
        $str_xml .=         '<Mapping ParentType="Series" ParentID="' . $str_video_id . '" ElementType="Program" ElementID="' . $str_index_id . '" ParentCode="' . $str_video_id . '" ElementCode="' . $str_index_id . '" Action="REGIST" Type="1"/>';
        $str_xml .=     '</Mappings>';
        $str_xml .= '</ADI>';

        return $str_xml;
    }

    /**
     * 转换中文乱码
     */
    private function _handle_iconv_encoding($str_text)
    {
        if (strtolower(substr(php_uname(), 0, 7)) == "windows")
        {//windows下执行

            $str_encoding = mb_detect_encoding($str_text,array('GBK','UTF-8','ASCII','JIS'));
            if(strtoupper($str_encoding) != 'UTF-8')
            {
                return iconv($str_encoding, 'UTF-8',$str_text);
            }
        }
        return $str_text;
    }

    /**
     * 注入主媒资至上游消息队列
     */
    private function _insert_video_message($file,$str_video_id,$str_release_time,$str_tag,$int_new_index)
    {
        $arr_category_name = explode('/',trim($file['file_url'])); $int_level = count($arr_category_name);
        $str_category_name = $int_level >= 2 ? $arr_category_name[$int_level - 2] : ($int_new_index > 1 ? '电视剧' : '电影');
        $str_xml = $this->_do_series(array(
            'nns_video_id'     => $str_video_id,
            'nns_video_name'   => $file['nns_video_name'],
            'nns_category_name'=> $str_category_name,
            'nns_release_time' => $str_release_time,
            'nns_view_type'    => $int_new_index > 1 ? 1 : 0,
            'nns_view_len'     => 0,
            'nns_all_index'    => $int_new_index,
            'nns_new_index'    => $int_new_index,
            'nns_tag'          => $str_tag,
        ));
        $this->_insert_message($str_video_id,$str_xml,1);
    }

    /**
     * 注入分集至上游消息队列
     */
    private function _insert_index_message($value,$str_video_id,$str_index_id,$str_index_name,$int_index,$str_tag)
    {
        $str_xml = $this->_do_program($str_video_id,array(
            'nns_index_id'    => $str_index_id,
            'nns_index_name'  => $str_index_name,
            'nns_sequence'    => $int_index,
            'nns_release_time'=> $value['nns_release_time'],
            'nns_view_len'    => $value['nns_file_size'],
            'nns_tag'         => $str_tag,
        ));
        $str_url = rtrim(pathinfo($value['nns_url'])['dirname'],'/') . '/' . $str_index_name;
        return $this->_insert_message($str_index_id,$str_xml,2);
    }

    /**
     * 注入片源至上游消息队列
     */
    private function _insert_media_message($value,$str_video_id,$str_index_id,$str_media_name,$str_extension,$str_mode,$str_tag)
    {
        $str_media_id = MD5($str_media_name . '.' . $str_extension . $this->str_cp_id);
        $str_xml = $this->_do_movie($str_video_id,$str_index_id,array(
            'nns_movie_id'     => $str_media_id,
            'nns_movie_url'    => parse_url($value['nns_url'])['path'],
            'nns_screen_format'=> '16x9',
            'nns_file_len'     => $value['nns_file_size'],
            'nns_file_size'    => $value['nns_file_size'],
            'nns_resolution'   => $value['nns_resolution'],
            'nns_bit_rate'     => $value['nns_bit_rate'],
            'nns_movie_mode'   => $str_mode,
            'nns_system_layer' => $this->_system_layer_media($str_extension),
            'nns_tag'          => $str_tag,
        ));
        $this->_insert_message($str_media_id,$str_xml,3);
    }

    /**
     * 向消息队列内部写入消息
     * @param string $str_message_id 媒资ID
     * @param string $str_xml        工单XML
     * @param int    $int_video_type 媒资类型。1主媒资；2分集；3片源
     * @return array|multitype
     */
    private function _insert_message($str_message_id,$str_xml,$int_video_type)
    {
        //验证媒资是否已经存在
        $result = nl_message::query_message_by_message_id($this->obj_dc, $str_message_id, $this->str_cp_id);
        if(isset($result['data_info']) && is_array($result['data_info']) && !empty($result['data_info']))
        {
            return m_config::return_data(0,"[内容已存在不再注入][消息ID：{$str_message_id}]");
        }
        $this->arr_in_message['base_info']['nns_action'] = 1;
        $this->arr_in_message['base_info']['nns_type']   = $int_video_type;
        $this->arr_in_message['base_info']['nns_message_id']  = $str_message_id;
        $this->arr_in_message['base_info']['nns_message_time']= microtime(true) * 10000;
        $this->arr_in_message['base_info']['nns_message_content'] = $str_xml;
        $result = $this->push($this->arr_in_message);

        return $result;
    }

    /**
     * 片源文件格式
     */
    private function _system_layer_media($str_extension)
    {
        switch (strtolower($str_extension))
        {
            case 'mp4':
                $SystemLayer = 3;
                break;
            case 'mpg':
                $SystemLayer = 4;
                break;
            case 'mts':
                $SystemLayer = 6;
                break;
            default:
                $SystemLayer = 1;
        }

        return $SystemLayer;
    }

}
$obj_import_ftp_media = new import_ftp_media($argv[1]);
$obj_import_ftp_media->init();